package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket;
    private String serverIP;
    private int serverPort;

    public UdpEchoClient(String serverIP, int serverPort) throws SocketException {
        //定位当前机器的位置，客户端不需要指定端口号，让用户那边的操作系统自行决定
        socket = new DatagramSocket();
        this.serverIP = serverIP;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {
        Scanner scan = new Scanner(System.in);
        while(true) {
            //用户从控制台输入要传输的数据
            System.out.println("请输入你要传输的数据：");
            if(!scan.hasNext()) {
                return;
            }
            String request = scan.nextLine();

            //构建请求数据包
            //注意要传入服务器的IP和端口号，否则数据包不知道发到哪里！！！
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(serverIP),serverPort);
            //发送数据包
            socket.send(requestPacket);

            //接收服务器传来的数据包
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);

            //解析响应数据包，然后打印出来
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.println("响应内容：" + response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
